import re
#
from django.db import transaction
from django.http import HttpResponse
from django.shortcuts import redirect
from requests import Response
from rest_framework.views import APIView
from rest_framework.response import Response
from utils.comm import send_message,get_redis
from django.core.paginator import Paginator
from users.ser import *
# from ronglian_sms_sdk import SmsSDK
# accId = '8a216da87ba59937017bf7ce78101547'
# accToken = '37e4238c564b4979ab1ade66ea0fc1c5'
# appId = '8a216da87ba59937017bf7ce78f3154e'
# import json
# def send_message(mobile,code,time):
#     sdk = SmsSDK(accId, accToken, appId)
#     tid = '1'
#     datas = (code, time)
#     resp = sdk.sendMessage(tid, mobile, datas)
#     result = json.loads(resp)
#     if result['statusCode'] == '000000':
#         return True
#     return False

# from django.core.paginator import Paginator
from .models import *
# from .ser import *
# # class NewAPIview(APIView):          # 添加
# #     def post(self,request):
# #         data=request.data
# #         ser=Newser(data=data)
# #         ser.is_valid(raise_exception=True)
# #         ser.save()
# #         return Response(ser.data,status=200)
# #     def get(self,request):         # 分页
# #         news=New.objects.all()
# #         p=Paginator(news,2)
# #         cpage=request.GET.get('page')
# #         newsR=p.page(cpage)
# #         ser=Newser(newsR)
# #         return Response({"code":200,'list':ser.data,'tpage':p.num_pages})
import redis

class Test(APIView):
    def get(self, request):
        # send_message('18530561795', '123', 1)
        get_redis()
        return Response('ok')
# 注册接口
class Register(APIView):
    def post(self, request):
        username = request.data.get('username')
        # 验证用户名是否为空
        if not username:
            return Response({'code': '10010', 'msg': '用户名不能为空'})
        # 格式是否正确
        name = re.match('\w{5,10}$', username)
        if not name:
            return Response({'code': '10011'})
        # 是否唯一
        user = User.objects.filter(username=username).first()
        if user:
            return Response({'code': '10012'})
        # 验证密码是否为空
        password = request.data.get('password')
        if not password:
            return Response({'code': '10013', 'msg': '密码不能为空'})
        # 密码格式是否正确
        pd = re.match('\w{8,20}$', password)
        if not pd:
            return Response({'msg': '密码格式不对', 'code': '10014'})
        # 手机号
        mobile = request.data.get('mobile')
        # 验证用户名是否为空
        if not mobile:
            return Response({'code': '10015', 'msg': '手机号不能为空'})
        # 格式是否正确
        phone = re.match('^1[3-9]\d{9}$', mobile)
        if not phone:
            return Response({'code': '10016'})
        # 是否唯一
        sloe = User.objects.filter(mobile=mobile).first()
        if sloe:
            return Response({'code': '10017'})
        # 验证码验证 newcode，redis取根据手机号
        smscode = request.data.get('smscode')
        conn = get_redis()
        code = conn.get(mobile)
        if code:
            code = str(code,encoding='utf8')
        if smscode != code:
            return Response({'code': '10018'})
        return Response({'code': 200, 'msg': '注册成功'})

# class TypeAPI(APIView):
#     def get(self, request):
#         data = Type.objects.all()
#         all_data = TypeModel(data, many=True)
#         return Response(all_data.data)

# class BooksAPI(APIView):
#     def get(self, request):
#         id = request.GET.get('id')
#         fid = request.GET.get('fid')
#         if fid:
#             if not id:
#                 ser = Books.objects.all()
#             else:
#                 ser = Books.objects.filter(eg=id)
#             page = Paginator(ser, 2)
#             page1 = page.page(fid)
#             all_data = ShowBooks(page1, many=True)
#             return Response({
#                 'data': all_data.data,
#                 'page_range': [i for i in page.page_range]
#             })
#         else:
#             data = Books.objects.all()
#             all_data = ShowBooks(data, many=True)
#             return Response(all_data.data)
import random
class SendSms(APIView):
    def post(self,request):
        mobile = request.data.get('mobile')
        codesms = random.randint(100000, 999999)
        res = send_message(mobile, str(codesms), 1)
        code = 10010
        if res:
            code = 200
            conn = get_redis()
            conn.setex(mobile, 60, codesms)
        return Response({'code': code})


# 发送短信验证码
# import random


# class SendMes(APIView):
#     def get(self, request):
#         # 接收客户端发送的数据
#         imagecode = request.GET.get('imagecode')
#         mobile = request.GET.get('mobile')
#         uuid = request.GET.get('uuid')
#         if not all([imagecode, mobile]):
#             return Response({'code': 10017})
#         # 验证图片验证码
#         conn = get_redis_conn()
#         # redis中取验证码
#         code = conn.get(uuid)
#
#         if code:
#             code = str(code, encoding='utf8')
#             # 图片验证码对比
#             if imagecode.lower() == code.lower():
#                 # 验证通过后调用发送短信接口
#                 sms_code = random.randint(10000, 99999)
#                 result = send_message(mobile, sms_code, 1)
#                 # 假如短信验证码发送成功
#                 if result:
#                     # redis存短信验证码
#                     conn.setex(mobile, 60, sms_code)
#                     # 把图片验证码从redis删除
#                     conn.delete(uuid)
#                     return Response({'code': 200})
#                 else:
#                     return Response({'code': 10020})
#             else:
#                 return Response({'code': 10019})
#         else:
#             return Response({'code': 10018})

from utils.captcha.captcha import captcha
class CreateC(APIView):
    def get(self,request):
        uuid=request.GET.get('uuid')
        name,text,img=captcha.generate_captcha()
        # conn=get_redis()
        # conn.set(uuid,text)
        return HttpResponse(img,content_type='image/jpg')
# class JournalismAPIView(APIView):
#     def get(self, request):
#         id = request.GET.get('id')
#         if not id:
#             data = Journalism.objects.all()
#             ser = JournalismSer(data, many=True)
#             return Response(ser.data)
#         else:
#             data = Journalism.objects.get(pk=id)
#             ser = JournalismSer(data)
#             return Response(ser.data)

class Moviemanage(APIView):
    def post(self,request):
        ser = Movieser(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code':200})
        else:
            print(ser.errors)
            return Response({'code':20010})
    def get(self,request):
        se = Movie.objects.all()
        ser = Movieser(se,many=True)
        return Response({'code':200,'list':ser.data})

class Actormanage(APIView):
    def post(self,request):
        ser = Actorser(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code':200})
        else:
            print(ser.errors)
            return Response({'code':20010})
    def get(self,request):
        se = Actor.objects.all()
        ser = Actorser(se,many=True)
        return Response({'code':200,'list':ser.data})


# A1作业
class Teachermanage(APIView):
    def post(self,request):
        ser = Teacherser(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 200})
        else:
            print(ser.errors)
            return Response({'code': 20010})
    def get(self,request):
        username = request.data.get('username')
        se = Teacher.objects.filter(username=username).all()
        ser = Teacherser(se,many=True)
        return Response({'code':200,'list':ser.data})

class TeacherM(APIView):
    def post(self,request):
        username = request.data.get('username')
        password = request.data.get('password')
        use = Teacher.objects.filter(username=username).all()
        if username==use.username:
            if password == use.password:
                return Response({'code':200,'userid':use.id})
            else:
                return Response({'code':20010,'meg':'密码错误'})
        else:
            return Response({'code':20011,'meg':'用户名不存在'})

class Studentmanage(APIView):
    def post(self,request):
        ser = Studentser(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 200})
        else:
            print(ser.errors)
            return Response({'code': 20010})

class AreaM(APIView):
    def get(self,request):
        pid = request.GET.get('pid')
        if not pid:
            #获取省
            areas = Area.objects.filter(parent_id__isnull=True).all()
        else:
            #获取市或者区
            areas = Area.objects.filter(parent_id=pid).all()

        ser = AreaSer(areas,many=True)
        return Response({"code":200,'list':ser.data})


def xTree(datas):
    list = []
    tree = {}
    for i in datas:
        tree[i['id']] = i

    for i in datas:
        parent = i['parent']
        if not parent:
            list.append(i)
        else:
            if 'son' not in tree[parent]:
                tree[parent]['son'] = []
            tree[parent]['son'].append(i)
    return list


# 读取def xTree(datas):
#     list=[]
#     tree={}
#     for i in datas:
#         tree[i['id']] = i
#
#     for i in datas:
#         parent = i['parent']
#         if not parent:
#             list.append(i)
#         else:
#             if 'son' not in tree[parent]:
#                 tree[parent]['son']=[]
#             tree[parent]['son'].append(i)
#     return list
#
# #读取首页三级分类
# class Home(APIView):
#     def get(self,request):
#         #读取一级
#         cates = Category.objects.filter(parent_id__isnull=True).all()
#         list=[]
#         for i in cates:
#             dict={}
#             dict['id'] = i.id
#             dict['name'] = i.name
#             #读取二级
#             two = i.subs.all()
#             twolist=[]
#             #遍历二级获取三级
#             for j in two:
#                 twodict={}
#                 twodict['id'] = j.id
#                 twodict['name'] = j.name
#                 three = j.subs.all()
#                 ser = CateSer(three,many=True)
#                 twodict['subs'] = ser.data
#                 twolist.append(twodict)
#
#             dict['subs'] = twolist
#             list.append(dict)
#         #查询一级分类，一级下面的二级，一级下面的三级，一级下面所有的商品
#         categoods=[]
#         for j in cates:
#             dict={}
#             dict['id'] = j.id
#             dict['name']=j.name
#             dict['pic'] = str(j.pic)
#             two = j.subs.all()
#             twoser = CateSer(two,many=True)
#             dict['two']=twoser.data
#             #获取三级
#             three = Category.objects.filter(top_parent=j.id,level=3).all()
#             threeser = CateSer(three,many=True)
#             dict['three']=threeser.data
#             #获取商品,排序，新品按时间倒序排，价格，销量
#             sorted = request.GET.get('sorted')
#             topid = request.GET.get('topid')
#
#             goods = Goods.objects.filter(category1_id=j.id,home_show=1).all()
#             if sorted:
#                 if int(topid) == int(j.id):
#                     goods = Goods.objects.filter(category1_id=j.id,home_show=1).order_by('-'+sorted).all()
#
#             gser = GoodsSer(goods,many=True)
#             dict['goods'] = gser.data
#             categoods.append(dict)
#         return Response({"code":200,'catelist':list,'categoods':categoods})




##读取首页三级分类
class Home(APIView):
    def get(self,request):
        #读取一级
        cates = Category.objects.filter(parent_id__isnull=True).all()
        list=[]
        for i in cates:
            dict={}
            dict['id'] = i.id
            dict['name'] = i.name
            #读取二级
            two = i.subs.all()
            print(two)
            twolist=[]
            #遍历二级获取三级
            for j in two:
                twodict={}
                twodict['id'] = j.id
                twodict['name'] = j.name
                three = j.subs.all()
                ser = CateSer(three,many=True)
                twodict['subs'] = ser.data
                twolist.append(twodict)

            dict['subs'] = twolist
            list.append(dict)
        return Response({"code":200,'catelist':list})

        # 查询一级分类，一级下面的二级，一级下面的三级，一级下面所有的商品
        categoods = []
        for j in cates:
            dict = {}
            dict['id'] = j.id
            dict['name'] = j.name
            dict['pic'] = str(j.pic)
            two = j.subs.all()
            twoser = CateSer(two, many=True)
            dict['two'] = twoser.data
            # 获取三级
            three = Category.objects.filter(top_parent=j.id, level=3).all()
            threeser = CateSer(three, many=True)
            dict['three'] = threeser.data
            # 获取商品,排序，新品按时间倒序排，价格，销量
            sorted = request.GET.get('sorted')
            topid = request.GET.get('topid')

            goods = Goods.objects.filter(category1_id=j.id, home_show=1).all()
            if sorted:
                if int(topid) == int(j.id):
                    goods = Goods.objects.filter(category1_id=j.id, home_show=1).order_by('-' + sorted).all()

            gser = GoodsSer(goods, many=True)
            dict['goods'] = gser.data
            categoods.append(dict)
        return Response({"code": 200, 'catelist': list, 'categoods': categoods})
# class GoodsM(APIView):
#     def get(self,request):
#         id = request.GET.get('id')
#         good = Goods.objects.filter(id=id).first()
#         ser = GoodsSer(good)
#         return Response({"code":200,'good':ser.data})
class CartM(APIView):
    def post(self,request):
        #判断此用户是否购买过此商品
        userid = request.data.get('user')
        goodsid = request.data.get('goods')
        number = int(request.data.get('number'))
        cart = Cart.objects.filter(user_id=userid,goods=goodsid).first()
        if cart:
        #如果买过数量+
            cart.number +=number
            cart.save()
            return Response({"code":200})
        else:
        #没买过购物车新增一条记录
            ser = CartSer(data=request.data)
            if ser.is_valid():
                ser.save()
                return Response({"code":200})
            else:
                print(ser.errors)
                return Response({"code":10010})
class CartM(APIView):
    def post(self,request):
        #判断此用户是否购买过此商品
        userid = request.data.get('user')
        goodsid = request.data.get('goods')
        number = int(request.data.get('number'))
        cart = Cart.objects.filter(user_id=userid,goods_id=goodsid).first()
        if cart:
        #如果买过数量+
            cart.number +=number
            cart.save()
            return Response({"code":200})
        else:
        #没买过购物车新增一条记录
            ser = CartSer(data=request.data)
            if ser.is_valid():
                ser.save()
                return Response({"code":200})
            else:
                print(ser.errors)
                return Response({"code":10010})
    # def get(self,request):
    #     userid = request.GET.get('userid')
    #     cart = Cart.objects.filter(user_id=userid).all()
    #     ser = ShowCartSer(cart,many=True)
    #     #全选
    #     selected_all = True
    #     total=0
    #     select_total=0
    #     select_money=0
    #     for i in cart:
    #         total+=i.number
    #         if i.is_checked == False:
    #             selected_all=False
    #         else:
    #             select_total+=i.number
    #             goods = Goods.objects.filter(id=i.goods_id).first()
    #             select_money+=i.number * float(goods.price)
    #
    #     return Response({"code":200,'list':ser.data,'selected_all':selected_all,'total':total,'select_total':select_total,'select_money':select_money})

    def put(self,request):
        id = request.GET.get('id')
        cart = Cart.objects.filter(id=id).first()
        if cart.is_checked == True:
            cart.is_checked=False
        else:
            cart.is_checked=True
        cart.save()
        return Response({"code":200})


#全选
class SelectAll(APIView):
    def put(self,request):
        userid = request.GET.get('userid')
        selected_all = request.GET.get('selected_all')
        if selected_all == 'true':
            Cart.objects.filter(user_id=userid).update(is_checked=True)
        else:
            Cart.objects.filter(user_id=userid).update(is_checked=False)
        return Response({'code':200})

    def post(self,request):
        id = request.data.get('id')
        type = request.data.get('type')
        count = request.data.get('count')
        cart = Cart.objects.filter(id=id).first()
        if type ==1:
            #加
             cart.number +=1
        elif type == 2:
            #减
            #判断是否>1
            if cart.number>1:
                cart.number -=1
        else:
            #数量更新
            cart.number = int(count)
        cart.save()
        return Response({"code":200})

#
class Showcourse(APIView):
    def get(self,request):
        sclass=Sclass.objects.all()
        ser=SclassSer(sclass,many=True)
        return Response({"code":200,'list':ser.data})

# class Show(APIView):
#     def get(self,request):
#         sclass=Sclass.objects.all()
#         ser=Studentser(sclass,many=True)
#         list=[]
#         for i in ser.data:
#             dict={}
#             dict['name']=i['name']
#             return Response({"code":200,"list":ser.data})

class reg(APIView):
    def post(self,request):
        ser=Studentser(data=request.data)
        if ser.is_valid():
            ser.save()
            stu=Stu.objects.filter(username=request.data.get('username')).first()
            return Response({"code":200,'id':stu.id,'name':stu})

class GetCheckedCart(APIView):
    def get(self,request):
        #获取userid
        userid = request.GET.get('userid')
        #通过userid,is_checked=true查询
        cart = Cart.objects.filter(user_id=userid,is_checked=True).all()
        ser = ShowCartSer(cart,many=True)
        total=0
        tmoney=0
        for i in ser.data:
            #查询总数量
            total +=i['number']
            #查询总金额
            tmoney += i['number'] * float(i['goods']['price'])
        #返回结果
        return Response({"code":200,'list':ser.data,'total':total,'tmoney':tmoney})

import time


class Pay(APIView):
    def get(self, request):
        alipay = get_ali_object()

        # 生成支付的url
        query_params = alipay.direct_pay(
            subject="test",  # 商品简单描述
            out_trade_no="myorder" + str(time.time()),  # 用户购买的商品订单号（每次不一样） 20180301073422891
            total_amount=100,  # 交易金额(单位: 元 保留俩位小数)
        )
        pay_url = "https://openapi.alipaydev.com/gateway.do?{0}".format(query_params)  # 支付宝网关地址（沙箱应用）
        return redirect(pay_url)


# 支付宝回调
class Notify(APIView):
    @transaction.atomic
    def get(self, request):
        # 订单号
        out_trade_no = request.GET.get('out_trade_no')
        # 支付宝的流水号
        trade_no = request.GET.get('trade_no')
        # 根据订单号查询订单
        orderinfo = OrderInfo.objects.filter(order_no=out_trade_no).first()
        sid = transaction.savepoint()
        try:
            if orderinfo and orderinfo.status == 1:
                # 订单的支付状态，是1
                # 支付成功后，更新订单状态
                orderinfo.status = 2
                orderinfo.transaction_no = trade_no
                orderinfo.save()
                # 查询订单详情，更新库存和销量
                # print(orderinfo.details)
                details = OrderDetail.objects.filter(order_id=out_trade_no).all()
                for i in details:
                    goods = Goods.objects.filter(id=i.goods_id).first()
                    goods.sales += i.count
                    goods.store -= i.count
                    goods.save()
            transaction.savepoint_commit(sid)
            return Response({'code': 200})
        except:
            transaction.savepoint_rollback(sid)
            return Response({'code': 40020})

    